<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>瞬影图床</title>
    <style>
        /* 基础样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            overflow: hidden;
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradientBG 15s ease infinite;
        }

        @keyframes gradientBG {
            0% {
                background-position: 0% 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0% 50%;
            }
        }

        .container {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            text-align: center;
            max-width: 500px;
            width: 100%;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        h1 {
            font-size: 2.5rem;
            color: #333;
            margin-bottom: 20px;
            animation: slideIn 1s ease-in-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-50px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .displayImgUrl {
            height: 300px;
            width: 100%;
            background-color: rgba(251, 194, 235, 0.8);
            margin: 20px auto;
            border-radius: 10px;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: flex-start;
            font-size: 16px;
            color: #333;
            box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
            transition: background-color 0.3s ease;
            padding: 10px;
            overflow-y: auto;
            word-break: break-all;
        }

        .displayImgUrl img {
            max-width: 100px;
            max-height: 100px;
            border-radius: 5px;
            margin: 5px;
        }

        .displayImgUrl:hover {
            background-color: rgba(251, 194, 235, 1);
        }

        form {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        input[type="file"] {
            display: none;
        }

        .custom-file-upload {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease, transform 0.2s ease;
            margin-bottom: 10px;
        }

        .custom-file-upload:hover {
            background-color: #0056b3;
            transform: scale(1.05);
        }

        .custom-file-upload:active {
            transform: scale(0.95);
        }

        button {
            padding: 10px 20px;
            background-color: #28a745;
            color: #fff;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease, transform 0.2s ease;
        }

        button:hover {
            background-color: #218838;
            transform: scale(1.05);
        }

        button:active {
            transform: scale(0.95);
        }

        .loading {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            z-index: 1000;
        }

        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-top: 4px solid #007bff;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        .progress-container {
            width: 200px;
            height: 10px;
            background-color: #f1f1f1;
            border-radius: 5px;
            margin: 10px auto;
            overflow: hidden;
        }

        .progress-bar {
            width: 0;
            height: 100%;
            background-color: #007bff;
            transition: width 0.3s ease;
        }

        .delete-btn {
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 5px 10px;
            cursor: pointer;
            margin-top: 5px;
            font-size: 12px;
            transition: background-color 0.3s ease;
        }

        .delete-btn:hover {
            background-color: #c82333;
        }

        .copy-btn {
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 5px 10px;
            cursor: pointer;
            margin-top: 5px;
            font-size: 12px;
            transition: background-color 0.3s ease;
        }

        .copy-btn:hover {
            background-color: #218838;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>瞬影图床</h1>
    <div class="displayImgUrl" id="displayImgUrl">
        <!-- 这里将显示多张图片及其 URL -->
    </div>
    <form id="uploadForm" enctype="multipart/form-data">
        <label for="imageInput" class="custom-file-upload">
            选择图片
        </label>
        <input type="file" id="imageInput" name="image" accept="image/*" multiple>
        <button type="button" id="clearButton" class="custom-file-upload">清除所有图片</button>
        <button type="submit">上传</button>
    </form>
</div>
<div class="loading" id="loading">
    <div class="spinner"></div>
    <div>上传中，请稍候...</div>
    <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const imageInput = document.getElementById('imageInput');
        const displayImgUrl = document.getElementById('displayImgUrl');
        const loading = document.getElementById('loading');
        const progressBar = document.getElementById('progressBar');
        const uploadForm = document.getElementById('uploadForm');
        const clearButton = document.getElementById('clearButton');

        let selectedFiles = []; // 用于存储所有选择的文件
        let deletedFiles = []; // 用于存储已删除的文件索引
        let existingFileNames = new Set(); // 用于存储已显示的文件名

        // 监听文件选择事件
        imageInput.addEventListener('change', function (event) {
            const newFiles = Array.from(event.target.files);
            selectedFiles = selectedFiles.concat(newFiles); // 合并新文件和已选择的文件

            // 清空显示区域
            displayImgUrl.innerHTML = '';
            existingFileNames.clear();

            selectedFiles.forEach((file, index) => {
                if (!existingFileNames.has(file.name)) {
                    existingFileNames.add(file.name); // 添加文件名到已显示的文件名集合
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        // 显示每张图片
                        const imgContainer = document.createElement('div');
                        imgContainer.style.margin = '10px';
                        imgContainer.dataset.fileIndex = index; // 添加文件索引
                        imgContainer.innerHTML = `
                                <img src="${e.target.result}" alt="Selected Image" style="max-width: 100px; max-height: 100px;">
                                <div>${file.name}</div>
                                <button class="delete-btn" onclick="deleteImage(${index})">删除</button>
                            `;
                        displayImgUrl.appendChild(imgContainer);
                    };
                    reader.readAsDataURL(file);
                }
            });
        });

        // 清除所有已选择图片
        clearButton.addEventListener('click', function () {
            selectedFiles = [];
            deletedFiles = [];
            existingFileNames.clear();
            displayImgUrl.innerHTML = '';
            imageInput.value = ''; // 清空文件输入框
        });

        // 监听表单提交事件
        uploadForm.addEventListener('submit', function (event) {
            event.preventDefault(); // 阻止表单默认提交行为

            const formData = new FormData();
            selectedFiles.forEach((file, index) => {
                if (!deletedFiles.includes(index)) { // 如果文件未被删除，则添加到 FormData
                    formData.append('image', file);
                }
            });

            const xhr = new XMLHttpRequest();

            // 显示加载动画
            loading.style.display = 'block';
            progressBar.style.width = '0%'; // 重置进度条

            xhr.open('POST', '/upload', true);

            // 监听上传进度
            xhr.upload.onprogress = function (event) {
                if (event.lengthComputable) {
                    const percentComplete = (event.loaded / event.total) * 100;
                    progressBar.style.width = percentComplete + '%';
                }
            };

            xhr.onload = function () {
                // 隐藏加载动画
                loading.style.display = 'none';

                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText); // 解析服务器返回的 JSON 对象
                    console.log('上传成功:', response);
                    displayImgUrl.innerHTML = ''; // 清空之前的内容
                    response.keys.forEach(key => {
                        const imgContainer = document.createElement('div');
                        imgContainer.style.margin = '10px';
                        imgContainer.innerHTML = `
                                <img src="${key}" alt="Uploaded Image" style="max-width: 100px; max-height: 100px;">
                                <div>${key}</div>
                                <button class="copy-btn" onclick="copyURL('${key}')">复制链接</button>
                                <button class="delete-btn" onclick="deleteUploadedImage('${key}')">删除</button>
                            `;
                        displayImgUrl.appendChild(imgContainer);
                    });
                    // 上传完成后，清空已选择的文件
                    selectedFiles = [];
                    deletedFiles = [];
                    existingFileNames.clear();
                    imageInput.value = ''; // 清空文件输入框
                } else {
                    console.error('上传失败:', xhr.responseText);
                    alert('上传失败，请重试！');
                }
            };

            xhr.send(formData); // 发送 FormData
        });

        // 删除图片的函数
        window.deleteImage = function (index) {
            deletedFiles.push(index); // 将删除的文件索引添加到数组
            const imgContainer = displayImgUrl.querySelector(`[data-file-index="${index}"]`);
            if (imgContainer) {
                imgContainer.remove(); // 从 DOM 中移除图片容器
            }
        };

        // 删除已上传图片的函数
        window.deleteUploadedImage = function (key) {
            if (confirm('确定要删除这张图片吗？')) {
                // 提取文件名（假设 key 的格式为 "<url id="" type="url" status="parsing" title="" wc="0">https://example.com/image.jpg&#34;）</url> 
                const fileName = key.split('/').pop(); // 仅提取文件名

                const xhr = new XMLHttpRequest();
                xhr.open('DELETE', `/image/${fileName}`, true); // 使用文件名作为删除的唯一标识

                xhr.onload = function () {
                    if (xhr.status === 200) {
                        console.log('删除成功:', xhr.responseText);
                        // 找到对应的图片容器并移除
                        const imgContainer = displayImgUrl.querySelector(`div img[src="${key}"]`).parentElement;
                        if (imgContainer) {
                            imgContainer.remove(); // 从 DOM 中移除图片容器
                        }
                    } else {
                        console.error('删除失败:', xhr.responseText);
                        alert('删除失败，请重试！');
                    }
                };

                xhr.send();
            }
        };

        // 复制 URL 的函数
        window.copyURL = function (url) {
            // 创建一个临时的 textarea 元素
            const textarea = document.createElement('textarea');
            textarea.value = url;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);

            alert('链接已复制到剪贴板！');
        };
    });
</script>
</body>
</html>